﻿using System;
using System.Web.UI.WebControls;
using Portal.Data.Helper;
using App_Code.Modules;
using Portal.Core;
using Portal.Core.Binding;
using Portal.Data.Entity;

public partial class Modules_Banner_Edit : BannerModule
{
    protected override string Action
    {
        get
        {
            return "edited";
        }
    }
    private Banner _currentObj, _editBanner;
    protected Banner EditBanner
    {
        get
        {
            if (_editBanner == null)
            {
                object obj = Binder.GetData(_currentObj, phContent, new BindContext());
                if (obj != null)
                {
                    _editBanner = (Banner)obj;
                }
            }
            return _editBanner;
        }
    }
    protected override void OnInit(EventArgs e)
    {
        if (!IsPostBack)
        {
            Positions.DataSource = ObjectBannerPositionClass.ListAll();
            Positions.DataBind();
        }

        _currentObj = (Banner)FindByPrimaryKey();

        Binder.SetData(phContent, _currentObj, new BindContext());

        //fill in list position
        var poss = BannerGroup.FindByBanner(_currentObj.ID);
        for (int i = 0; i < poss.Count; i++)
        {
            var id = ((BannerGroup)poss[i]).GroupID.ToString();
            foreach (ListItem item in Positions.Items)
            {
                if (item.Value.Equals(id))
                    item.Selected = true;
            }
        }

    }
    protected override void Save_Click(object sender, EventArgs e)
    {
        EditBanner.IsText = !string.IsNullOrEmpty(EditBanner.DisplayText) && string.IsNullOrEmpty(EditBanner.Path);
        EditBanner.Update();

        //remove old
        BannerGroup.RemoveByBanner(EditBanner.ID);

        //save new
        foreach (ListItem item in Positions.Items)
        {
            if (item.Selected)
            {
                var pos = Convert.ToInt32(item.Value);
                var bg = new BannerGroup { BannerID = EditBanner.ID, GroupID = pos };
                ORMHelper.InstanceIgnorePermission.Save(bg);
            }
        }

        Forward("Save");
    }
}